# coding:utf-8
from django.http import JsonResponse
from shop.models import *
from uuid import UUID


def get_all_restaurant(request):
    """
    查询指定大学所有餐厅的信息
    :param request: 请求信息
    :return: Json响应，内容包含指定大学的所有餐厅的信息
    """
    # 请求方法为POST
    if request.method == 'POST':
        post_data = request.POST
        # 请求信息中未提供大学编号
        if 'university_id' not in post_data:
            return JsonResponse({'error': '没有提供大学编号'}, status=400)
        # 从请求信息中获取大学编号
        university_id = post_data['university_id']
        try:
            # 将编号转化为UUID
            university_uuid = UUID(university_id)
        # 所提供的编号不是UUID
        except ValueError:
            return JsonResponse({'error': '错误的大学编号格式'}, status=400)
        university_set = University.objects.filter(id=university_uuid)
        # 没有在数据库中找到对应编号的大学
        if university_set.count() != 1:
            return JsonResponse({'error': '大学编号不存在'}, status=400)
        restaurant_set = Restaurant.objects.filter(university_id=university_uuid)
        results = list()
        for restaurant in restaurant_set:
            rt_dic = dict()
            rt_dic['id'] = restaurant.id
            rt_dic['name'] = restaurant.name
            rt_dic['university_id'] = restaurant.university_id
            results.append(rt_dic)
        return JsonResponse(results, safe=False, status=200)
    # 请求方法不满足要求，返回'405 Method Not Allowed'错
    else:
        return JsonResponse({'error': '错误的请求方法'}, status=405)


def get_all_shop(request):
    """
    查询指定餐厅的所有店家信息
    :param request:请求信息
    :return: Json响应，包含指定餐厅的所有店家信息
    """
    # 请求方法为POST
    if request.method == 'POST':
        post_data = request.POST
        # 请求中未提供餐厅编号
        if 'restaurant_id' not in post_data:
            return JsonResponse({'error': '未提供餐厅编号'}, status=400)
        # 从请求中获取餐厅编号
        restaurant_id = post_data['restaurant_id']
        try:
            # 将编号转化为UUID
            restaurant_uuid = UUID(restaurant_id)
        # 所提供的编号不是UUID
        except ValueError:
            return JsonResponse({'error': '错误的餐厅编号格式'}, status=400)
        restaurant_set = Restaurant.objects.filter(id=restaurant_uuid)
        if restaurant_set.count() != 1:
            return JsonResponse({'error': '餐厅编号不存在'}, status=400)
        shop_set = Seller.objects.filter(restaurant_id=restaurant_uuid)
        order_key = {
            'popularity': '-grade',
            'sales': '-sales',
        }
        if 'rank_by' not in post_data:
            shop_set = shop_set.order_by('-grade')
        elif post_data['rank_by'] in order_key:
            shop_set = shop_set.order_by(order_key[post_data['rank_by']])
        else:
            return JsonResponse({'error': '不支持的排序方式'}, status=400)
        # 页数，默认是1
        page = 1
        # 每页中店家的个数，默认是10
        number_per_page = 10
        if 'number_per_page' in post_data:
            number_per_page = int(post_data['number_per_page'])
        if 'page' in post_data:
            page = int(post_data['page'])
        starts = (page - 1) * number_per_page
        ends = page * number_per_page
        count = shop_set.count()
        results = {
            'last_page': ends >= count,
            'shops': [],
        }
        shop_set = shop_set[starts: ends]
        for shop in shop_set:
            shop_dic = dict()
            shop_dic['id'] = shop.id
            shop_dic['phone'] = shop.phone
            shop_dic['restaurant_id'] = shop.restaurant_id
            shop_dic['storey'] = shop.storey
            shop_dic['window'] = shop.window
            shop_dic['name'] = shop.name
            shop_dic['grade'] = shop.grade
            shop_dic['sales'] = shop.sales
            # TODO 图片信息
            results['shops'].append(shop_dic)
        return JsonResponse(results, status=200)
    # 请求方法不满足要求，返回'405 Method Not Allowed'错
    else:
        return JsonResponse({'error': '错误的请求方法'}, status=405)


def get_all_food(request):
    """
    获取某餐厅所有食物的列表
    :param request:请求信息
    :return: Json响应，包含某餐厅所有食物的信息
    """
    # 请求方法为POST
    if request.method == 'POST':
        post_data = request.POST
        # 请求中未提供餐厅编号
        if 'restaurant_id' not in post_data:
            return JsonResponse({'error': '未提供餐厅编号'}, status=400)
        # 从请求中获取餐厅编号
        restaurant_id = post_data['restaurant_id']
        try:
            # 将编号转化为UUID
            restaurant_uuid = UUID(restaurant_id)
        # 所提供的编号不是UUID
        except ValueError:
            return JsonResponse({'error': '错误的餐厅编号格式'}, status=400)
        restaurant_set = Restaurant.objects.filter(id=restaurant_uuid)
        if restaurant_set.count() != 1:
            return JsonResponse({'error': '餐厅编号不存在'}, status=400)
        # status=0表示食物的状态为'VALID'
        food_set = Food.objects.filter(seller__restaurant_id=restaurant_uuid, status=0)
        order_key = {
            'poluarity': '-grade',
            'sales': '-sales',
            'price_ascend': 'price',
            'price_descend': '-price',
            'last_add': '-create_time',
            'first_add': 'create_time',
        }
        if 'rank_by' not in post_data:
            food_set = food_set.order_by('-grade')
        elif post_data['rank_by'] in order_key:
            food_set = food_set.order_by(order_key[post_data['rank_by']])
        else:
            return JsonResponse({'error': '不支持的排序方式'}, status=400)
        # 页数，默认是1
        page = 1
        # 每页中食物的个数，默认是10
        number_per_page = 10
        if 'number_per_page' in post_data:
            number_per_page = int(post_data['number_per_page'])
        if 'page' in post_data:
            page = int(post_data['page'])
        starts = (page - 1) * number_per_page
        ends = page * number_per_page
        count = food_set.count()
        results = {
            'last_page': ends >= count,
            'food': [],
        }
        food_set = food_set[starts: ends]
        for food in food_set:
            food_dic = dict()
            food_dic['id'] = food.id
            food_dic['seller'] = food.seller_id
            food_dic['name'] = food.name
            food_dic['grade'] = food.grade
            food_dic['sales'] = food.sales
            # TODO 图片信息
            results['food'].append(food_dic)
        return JsonResponse(results, status=200)
    # 请求方法不满足要求，返回'405 Method Not Allowed'错
    else:
        return JsonResponse({'error': '错误的请求方法'}, status=405)


def get_information(request):
    """
    获取指定餐厅的信息
    :param request: 请求信息
    :return: Json响应，包含餐厅的信息
    """
    if request.method == 'POST':
        post_data = request.POST
        if 'restaurant_id' not in post_data:
            return JsonResponse({'error': '未提供给餐厅编号'})
        restaurant_id = post_data['restaurant_id']
        try:
            # 将编号转化为UUID
            restaurant_uuid = UUID(restaurant_id)
        # 所提供的编号不是UUID
        except ValueError:
            return JsonResponse({'error': '错误的餐厅编号格式'}, status=400)
        restaurant_set = Restaurant.objects.filter(id=restaurant_uuid)
        if restaurant_set.count() != 1:
            return JsonResponse({'error': '餐厅编号不存在'}, status=400)
        restaurant = restaurant_set[0]
        result = {
            'restaurant_id': restaurant.id,
            'name': restaurant.name,
            'university_id': restaurant.university_id
        }
        return JsonResponse(result, status=200)
    else:
        return JsonResponse({'error': '错误的请求方法'}, status=405)